package handler

import (
	"github.com/julienschmidt/httprouter"
	"net/http"
	//"os"
	//"io"
	"time"
	"path"
	"strings"
	"fmt"
	"os"
	"io"
	"encoding/json"
)

type FileInfoResponse struct {
	UID    int64  `json:"uid"`
	Name   string `json:"name`
	Status string `json:"status`
	Url    string `json:"url"`
	Response string `json:"response"`
}

func uploadImage( r *http.Request ) (response FileInfoResponse, err error) {
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("itembank-image")
	if err != nil {
		fmt.Println(err)
		return response, err
	}
	defer file.Close()

	//filename := renameFile(handler.Filename)
	filename := handler.Filename
	fullfilename := "/upload/img/"+filename
	targetPath := "."
	url := "/static/" + filename
	f, err := os.OpenFile(targetPath+fullfilename, os.O_WRONLY|os.O_CREATE, 0666)  // 此处假设当前目录下已存在test目录
	if err != nil {
		fmt.Println(err)
		return response, err
	}
	defer f.Close()
	io.Copy(f, file)

	response = FileInfoResponse{UID: 1, Name: filename, Status: "done", Url: url,Response:"hello"}
	return response,nil
}


func UploadImage(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("itembank-image")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()

	//filename := renameFile(handler.Filename)
	filename := handler.Filename
	fullfilename := "/upload/img/"+filename
	fmt.Printf("full filename %s \n", fullfilename)
	targetPath := "."
	url := "/static/" + filename
	f, err := os.OpenFile(targetPath+fullfilename, os.O_WRONLY|os.O_CREATE, 0666)  // 此处假设当前目录下已存在test目录
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	io.Copy(f, file)

	response := &FileInfoResponse{UID: 1, Name: filename, Status: "done", Url: url,Response:"hello"}
	b, err := json.Marshal(response)
	if err != nil {
		fmt.Printf("errors :", err)
	}
	w.Write(b)
}


func renameFile(filename string) string {
	t := time.Now()

	var filenameWithSuffix string
	filenameWithSuffix = path.Base(filename)

	var fileSuffix string
	fileSuffix = path.Ext(filenameWithSuffix) //获取文件后缀

	var filenameOnly string
	filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix) //获取文件名

	return filenameOnly + t.String() +  fileSuffix


}